#include "phoneloginwidget.h"
#include "model/datacenter.h"
#include "toast.h"
#include "mainwidget.h"
#include "loginwidget.h"

#include <QGridLayout>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>

using namespace model;

PhoneLoginWidget::PhoneLoginWidget(QWidget *parent)
    : QWidget{parent}
{
    // 1. 设置窗口的基本属性
    this->setFixedSize(400, 350);
    this->setWindowTitle("登录");
    this->setWindowIcon(QIcon(":/resource/image/logo.png"));
    this->setStyleSheet("QWidget { background-color: rgb(255, 255, 255); }");
    this->setAttribute(Qt::WA_DeleteOnClose);

    // 2. 创建核心布局管理器
    QGridLayout* layout = new QGridLayout();
    layout->setSpacing(10);
    layout->setContentsMargins(50, 0, 50, 0);
    this->setLayout(layout);

    // 3. 创建标题
    titleLabel = new QLabel();
    titleLabel->setText("登录");
    titleLabel->setFixedHeight(50);
    titleLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    titleLabel->setStyleSheet("QLabel { font-size: 40px; font-weight: 600; }");
    titleLabel->setAlignment(Qt::AlignCenter);

    // 4. 创建手机号输入框
    QString editStyle = "QLineEdit { border: none; background-color: rgb(240, 240, 240); font-size: 20px; border-radius: 10px; padding-left: 5px;}";
    phoneEdit = new QLineEdit();
    phoneEdit->setPlaceholderText("输入手机号");
    phoneEdit->setFixedHeight(40);
    phoneEdit->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    phoneEdit->setStyleSheet(editStyle);

    // 5. 创建验证码输入框
    verifyCodeEdit = new QLineEdit();
    verifyCodeEdit->setPlaceholderText("输入短信验证码");
    verifyCodeEdit->setFixedHeight(40);
    verifyCodeEdit->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    verifyCodeEdit->setStyleSheet(editStyle);

    // 6. 创建发送验证码按钮
    QString btnWhiteStyle = "QPushButton { border: none; border-radius: 10px; background-color: transparent; }";
    btnWhiteStyle += "QPushButton:pressed { background-color: rgb(240, 240, 240); }";
    sendVerifyCodeBtn = new QPushButton();
    sendVerifyCodeBtn->setFixedSize(100, 40);
    sendVerifyCodeBtn->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    sendVerifyCodeBtn->setText("发送验证码");
    sendVerifyCodeBtn->setStyleSheet(btnWhiteStyle);

    // 7. 创建提交按钮
    submitBtn = new QPushButton();
    submitBtn->setFixedHeight(40);
    submitBtn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    submitBtn->setText("登录");
    QString btnGreenStyle = "QPushButton { border: none; border-radius: 10px; background-color: rgb(44, 182, 61); color: rgb(255, 255, 255); }";
    btnGreenStyle += "QPushButton:pressed { background-color: rgb(240, 240, 240); }";
    submitBtn->setStyleSheet(btnGreenStyle);

    // 8. 创建 "切换到用户名" 模式按钮
    QPushButton* userModeBtn = new QPushButton();
    userModeBtn->setFixedSize(100, 40);
    userModeBtn->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    userModeBtn->setText("切换到用户名");
    userModeBtn->setStyleSheet(btnWhiteStyle);

    // 9. 切换登录注册模式
    switchModeBtn = new QPushButton();
    switchModeBtn->setFixedSize(100, 40);
    switchModeBtn->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    switchModeBtn->setText("注册");
    switchModeBtn->setStyleSheet(btnWhiteStyle);

    // 10. 添加到布局管理器
    layout->addWidget(titleLabel, 0, 0, 1, 5);
    layout->addWidget(phoneEdit, 1, 0, 1, 5);
    layout->addWidget(verifyCodeEdit, 2, 0, 1, 4);
    layout->addWidget(sendVerifyCodeBtn, 2, 4, 1, 1);
    layout->addWidget(submitBtn, 3, 0, 1, 5);
    layout->addWidget(userModeBtn, 4, 0, 1, 1);
    layout->addWidget(switchModeBtn, 4, 4, 1, 1);

    // 11. 添加信号槽
    connect(switchModeBtn, &QPushButton::clicked, this, &PhoneLoginWidget::switchMode);

    connect(userModeBtn, &QPushButton::clicked, this, [=]() {
        LoginWidget* loginWidget = new LoginWidget(nullptr);
        loginWidget->show();
        this->close();
    });

    //绑定发送验证码
    connect(sendVerifyCodeBtn, &QPushButton::clicked, this, &PhoneLoginWidget::sendVerifyCode);

    // timer = new QTimer(this);
    // connect(timer, &QTimer::timeout, this, &PhoneLoginWidget::countDown);

    // 提交按钮
    connect(submitBtn, &QPushButton::clicked, this, &PhoneLoginWidget::submitBtnClicked);
}


void PhoneLoginWidget::switchMode()
{
    if (isLoginMode) {
        // 切换到注册模式
        this->setWindowTitle("注册");
        titleLabel->setText("注册");
        submitBtn->setText("注册");
        switchModeBtn->setText("登录");
    } else {
        // 切换到登录模式
        this->setWindowTitle("登录");
        titleLabel->setText("登录");
        submitBtn->setText("登录");
        switchModeBtn->setText("注册");
    }
    isLoginMode = !isLoginMode;

    cooldown = 10;
}

void PhoneLoginWidget::sendVerifyCode()
{
    //获取手机号
    QString phoneNumber = phoneEdit->text();
    if (phoneNumber.isEmpty())
    {
        return;
    }
    //记录哪个手机号发送的验证码
    currentPhoneNumber = phoneNumber;
    //发送验证码
    DataCenter* dataCenter = DataCenter::getInstance();
    connect(dataCenter, &DataCenter::getVerifyCodeDone, this, &PhoneLoginWidget::sendVerifyCodeDone, Qt::UniqueConnection);
    dataCenter->getVerifyCodeAsync(phoneNumber);

    //开始倒计时
    countDown();
}

void PhoneLoginWidget::sendVerifyCodeDone()
{
    Toast::showMessage("验证码已发送");
}

void PhoneLoginWidget::countDown()
{
    sendVerifyCodeBtn->setEnabled(false);
    cooldown = 30;
    QTimer* timer = new QTimer(this);
    sendVerifyCodeBtn->setText(QString::number(cooldown) + "s后重发");

    connect(timer, &QTimer::timeout, this, [=](){
        cooldown--;
        if (cooldown <= 0) {
            sendVerifyCodeBtn->setText("获取验证码");
            sendVerifyCodeBtn->setEnabled(true);
            timer->stop();
            timer->deleteLater();
        } else {
            sendVerifyCodeBtn->setText(QString::number(cooldown) + "s后重发");
        }
    });
    timer->start(1000); // 每1秒触发一次
}

void PhoneLoginWidget::submitBtnClicked()
{
    // 获取手机号和验证码
    QString phoneNumber = this->currentPhoneNumber;
    QString verifyCode = verifyCodeEdit->text();
    if (phoneNumber.isEmpty() || verifyCode.isEmpty())
    {
        Toast::showMessage("请输入手机号和验证码");
        return;
    }
    // 调用 DataCenter 进行登录或注册
    DataCenter* dataCenter = DataCenter::getInstance();
    if (isLoginMode)
    {
        //登录
        connect(dataCenter, &DataCenter::phoneLoginDone, this, &PhoneLoginWidget::phoneLoginDone, Qt::UniqueConnection);
        dataCenter->phoneLoginAsync(phoneNumber, verifyCode);
    }
    else
    {
        //注册
        Toast::showMessage("该应用未通过工信部备案，您无法收到验证码，但手机号已经入数据库保存 详情私聊开发者", 6000);
        connect(dataCenter, &DataCenter::phoneRegisterDone, this, &PhoneLoginWidget::phoneRegisterDone, Qt::UniqueConnection);
        dataCenter->phoneRegisterAsync(phoneNumber, verifyCode);
    }
}

void PhoneLoginWidget::phoneLoginDone(bool success, const QString& reason)
{
    if (!success)
    {
        if(reason == "尝试登录的手机号码格式不正确")
            Toast::showMessage("登录失败: " + reason + " 请获取验证码以更新输入的手机号", 4000);
        else
            Toast::showMessage("登录失败: " + reason);
        return;
    }
    // 登录成功
    Toast::showMessage("登录成功");
    // 打开主窗口
    MainWidget* mainWidget = MainWidget::getInstance();
    mainWidget->show();
    // 关闭当前窗口
    this->close();
}

void PhoneLoginWidget::phoneRegisterDone(bool success, const QString& reason)
{
    if(!success)
    {
        Toast::showMessage("注册失败: " + reason);
        return;
    }
    //注册成功
    Toast::showMessage("注册成功, 请登录", 4000);
    //切换到登录模式
    switchMode();

    // 清空验证码输入框
    verifyCodeEdit->clear();


}















